package com.acquisition.config.security.service;

import com.acquisition.entity.SysPermission;
import com.acquisition.entity.SysUser;
import com.acquisition.service.SysPermissionService;
import com.acquisition.service.SysUserService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.List;

/**
 * @Author Jay Chou
 * @Description 登录认证实现类
 * @Date 2023-04-12 10:29
 **/
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            throw new BadCredentialsException("用户名为空");
        }
        //根据账号查询用户
        SysUser sysUser = sysUserService.queryByAccount(username);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (sysUser != null) {
            //获取该用户所拥有的权限
            List<SysPermission> sysPermissions = sysPermissionService.queryPermissionListByUserId(sysUser.getId());
            // 声明用户授权
            for (int i = 0; i < sysPermissions.size(); i++) {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermissions.get(i).getPermissionCode());
                grantedAuthorities.add(grantedAuthority);
            }
//            sysPermissions.forEach(sysPermission -> {
//                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
//                grantedAuthorities.add(grantedAuthority);
//            });
        }
        return new User(sysUser.getAccount(), sysUser.getPassword(), sysUser.getEnabled(), sysUser.getAccountNonExpired(), sysUser.getCredentialsNonExpired(), sysUser.getAccountNonLocked(), grantedAuthorities);
    }
}
